package com.lbd.gulimall.order.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.lbd.common.to.MemberEntity;
import com.lbd.common.to.SkuHasStockVo;
import com.lbd.common.utils.R;
import com.lbd.gulimall.order.feign.CartFeignService;
import com.lbd.gulimall.order.feign.MemberFeignService;
import com.lbd.gulimall.order.feign.WareFeignService;
import com.lbd.gulimall.order.interceptor.OrderInterceptor;
import com.lbd.gulimall.order.vo.MemberReceiveAddressVO;
import com.lbd.gulimall.order.vo.OrderConfirmVO;
import com.lbd.gulimall.order.vo.OrderItemVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lbd.common.utils.PageUtils;
import com.lbd.common.utils.Query;

import com.lbd.gulimall.order.dao.OrderDao;
import com.lbd.gulimall.order.entity.OrderEntity;
import com.lbd.gulimall.order.service.OrderService;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;


@Service("orderService")
public class OrderServiceImpl extends ServiceImpl<OrderDao, OrderEntity> implements OrderService {
    @Autowired
    private CartFeignService cartFeignService;
    @Autowired
    private MemberFeignService memberFeignService;
    @Autowired
    private WareFeignService wareFeignService;
    @Autowired
    private ThreadPoolExecutor executor;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<OrderEntity> page = this.page(
                new Query<OrderEntity>().getPage(params),
                new QueryWrapper<OrderEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public OrderConfirmVO getOrderConfirmInfo() throws ExecutionException, InterruptedException {
        MemberEntity member = OrderInterceptor.onlineUser.get();
        OrderConfirmVO confirmVO = new OrderConfirmVO();
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        //设置收货地址
        CompletableFuture<Void> memberFuture = CompletableFuture.runAsync(() -> {
            RequestContextHolder.setRequestAttributes(requestAttributes);
            R r = memberFeignService.getListByMemberId(member.getId());
            if (r.getCode() == 0) {
                List<MemberReceiveAddressVO> data = r.getData(new TypeReference<List<MemberReceiveAddressVO>>() {
                });
                confirmVO.setMemberReceiveAddress(data);
            }
        }, executor);
        //设置订单项
        CompletableFuture<List<OrderItemVO>> orderFuture = CompletableFuture.supplyAsync(() -> {
            RequestContextHolder.setRequestAttributes(requestAttributes);
            R r = cartFeignService.getAllSelectedCartItem();
            if (r.getCode() == 0) {
                List<OrderItemVO> data = r.getData(new TypeReference<List<OrderItemVO>>() {
                });
                confirmVO.setOrderItems(data);
                return data;
            }
            return null;
        }, executor);
        CompletableFuture<Void> wareFuture = orderFuture.thenAcceptAsync((orderItems) -> {
            //调用仓储微服务。这里涉及远程调用，对网络资源开销大，因此在循环外步骤只执行一次，存入map内存。通过skuId来获取各自是否有库存
            List<Long> skuIds = orderItems.stream().map(OrderItemVO::getSkuId).collect(Collectors.toList());
            R r = wareFeignService.hasStock(skuIds);
            //key为skuId，value为是否有库存
            Map<Long, Boolean> stockMap = r.getData(new TypeReference<List<SkuHasStockVo>>() {
                    }).stream()
                    .collect(Collectors.toMap(key -> key.getSkuId(), value -> value.getHasStock()));
            orderItems.forEach(orderItem -> {
                orderItem.setHasStock(stockMap.get(orderItem.getSkuId()));
            });
        }, executor);
        //设置会员积分
        confirmVO.setIntegration(member.getIntegration());
        //订单总额，应付价格。自动计算
        //设置订单防重复令牌
        confirmVO.setOrderToken(UUID.randomUUID().toString());
        CompletableFuture.allOf(memberFuture, wareFuture).get();
        return confirmVO;
    }

}